package cn.tinlan.shopcoin.app.mine.set;


import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.util.FileUtils;
import com.bumptech.glide.util.Util;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.widget.category.Constants;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Mortimer on 2018/11/27. 14:13
 * 佛祖🙏，永无bug。
 */
public class MineSettingActivity extends BaseActivity implements View.OnClickListener,EasyPermissions.PermissionCallbacks{


    @BindView(R.id.order_titlebar)
    TitleBar titleBar;
    @BindView(R.id.set_logout)
    Button logoutBtn;
    @BindView(R.id.set_qrcode)
    View qrCode;


    public static final int PERMISSIONS_CODE_1 = 101;
    public static final int RESULT_CODE_1 = 201;
    public static final int RESULT_CODE_2 = 202;
    /**
     * 需要的权限
     */
    private String[] mPerms = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    /**
     * 7.0 以上的uri
     */
    private Uri mProviderUri;
    /**
     * 7.0 以下的uri
     */
    private Uri mUri;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_mine_set;

    }

    @Override
    public void initView() {
        super.initView();

        drawableDefaultBar();

        initTitleBar();
        bindSubViewClickEvents();
    }

    private void initTitleBar() {
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
    }

    private void bindSubViewClickEvents() {
        logoutBtn.setOnClickListener(this);
        qrCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.set_logout:
                logout();
                break;
            case R.id.set_qrcode:
                startActivity(new Intent(MineSettingActivity.this,QRCodeActivity.class));
                break;
        }


    }


    private  void logout() {
        SPUtils.clear(MineSettingActivity.this);
        finish();
    }


    /**
     * 拍照
     */
    private void openCamera() {
        // 判断权限
        if (EasyPermissions.hasPermissions(MineSettingActivity.this, mPerms)) {

        } else {
            // 如果用户拒绝权限，第二次打开才会显示提示文字
            EasyPermissions.requestPermissions(this, "使用拍照功能需要拍照权限！", PERMISSIONS_CODE_1, mPerms);
        }
    }

    private void toCamera() {
        File file = new File(Constants.SAVE_REAL_PATH, System.currentTimeMillis() + ".jpg");
//        LogUtils.e(file.getPath());
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //Android7.0以上URI
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            mProviderUri = FileProvider.getUriForFile(MineSettingActivity.this, "com.sdwfqin.sample.fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mProviderUri);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            mUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        }
        try {
//            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            startActivityForResult(intent, RESULT_CODE_1);
        } catch (ActivityNotFoundException anf) {
            ToastUtils.show("摄像头未准备好！");
        }
    }
    /**
     * 相册选图
     */
    private void openPhotos() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(pickIntent, RESULT_CODE_2);
    }



    /**
     * 使用UCrop进行图片剪裁
     *
     * @param uri
     */
    public void cropRawPhoto(Uri uri) {

        UCrop.Options options = new UCrop.Options();
        // 修改标题栏颜色
        options.setToolbarColor(getResources().getColor(R.color.colorPrimary));
        // 修改状态栏颜色
        options.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        // 隐藏底部工具
        options.setHideBottomControls(true);
        // 图片格式
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        // 设置图片压缩质量
        options.setCompressionQuality(100);
        // 是否让用户调整范围(默认false)，如果开启，可能会造成剪切的图片的长宽比不是设定的
        // 如果不开启，用户不能拖动选框，只能缩放图片
        options.setFreeStyleCropEnabled(true);
        // 设置图片压缩质量
        options.setCompressionQuality(100);
        // 圆
        options.setCircleDimmedLayer(true);
        // 不显示网格线
        options.setShowCropGrid(false);

        FileUtils.createOrExistsDir(Constants.SAVE_REAL_PATH);

        // 设置源uri及目标uri
        UCrop.of(uri, Uri.fromFile(new File(Constants.SAVE_REAL_PATH, System.currentTimeMillis() + ".jpg")))
                // 长宽比
                .withAspectRatio(1, 1)
                // 图片大小
                .withMaxResultSize(200, 200)
                // 配置参数
                .withOptions(options)
                .start(MineSettingActivity.this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == UCrop.RESULT_ERROR) {
//            mCameraTv.setText(UCrop.getError(data) + "");

            return;
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RESULT_CODE_1:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cropRawPhoto(mProviderUri);
                    } else {
                        cropRawPhoto(mUri);
                    }
                    break;
                case RESULT_CODE_2:
//                    LogUtils.i("onActivityResult: " + data.getData());
                    cropRawPhoto(data.getData());
                    break;
                case UCrop.REQUEST_CROP:
//                    LogUtils.i("onActivityResult: " + UCrop.getOutput(data));
//                    mCameraTv.setText(UCrop.getOutput(data) + "");
//                    Glide.with(this)
//                            .load(UCrop.getOutput(data))
//                            .into(mCameraImg);
                    break;
                default:
                    break;
            }
        }
    }

    public Bitmap dealImageData(int requestCode, int resultCode, Intent data) {
//        try {
//            if (requestCode == RESULT_CAMERA) {
//                //从拍照回来的
//                if (!TextUtils.isEmpty(targetCameraPath)) {
//                    //ImageZipUtils是一个图片压缩工具
//                    String imagePath = targetCameraPath = ImageZipUtils.saveBitmap(activity, targetCameraPath);
//                    return BitmapFactory.decodeFile(imagePath);
//                }
//            } else if (requestCode == RESULT_ALBUM) {
//                //获得照片资源的原始地址
//                Uri originalUri = data.getData();
//                if (originalUri != null) {
//                    String[] proj = {MediaStore.Images.Media.DATA};
//                    Cursor cursor = activity.managedQuery(originalUri, proj, null, null, null);
//                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//                    cursor.moveToFirst();
//                    String imagePath = cursor.getString(column_index);
//                    if (!TextUtils.isEmpty(imagePath)) {
//                        imagePath = ImageZipUtils.saveBitmap(activity, imagePath);
//                        return BitmapFactory.decodeFile(imagePath);
//                    }
//                } else {
////                    ToastUtils.showToast("从相册获取图片失败");
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return null;
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
//        LogUtils.i("onPermissionsGranted: " + "同意授权");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ToastUtils.show("没有权限可能会引起程序崩溃");

        /**
         * 跳转到 APP 详情的权限设置页
         *
         * 可根据自己的需求定制对话框，点击某个按钮在执行下面的代码
         */
        Intent intent = getAppDetailSettingIntent(MineSettingActivity.this);
        startActivity(intent);

    }

    /**
     * 获取 APP 详情页面intent
     *
     * @return
     */
    public static Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        return localIntent;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
